﻿#include "myMusic.h"
#include "ui_myMusic.h"
#include <QMouseEvent>
#include <QGraphicsDropShadowEffect>
#include <QDebug>
#include <QIcon>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <time.h>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget),
    currentMusicIndix(-1)
{
    ui->setupUi(this);
    initUi();
    initSqlite();
    initPlayer();
    randomPicture();
    connectSignalAndSlot();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::initUi()
{
    // 设置无边框窗⼝，即窗口将来无标题栏
    setWindowFlag(Qt::WindowType::FramelessWindowHint);

    //将窗口背景调成透明
    this->setAttribute(Qt::WA_TranslucentBackground);

    setWindowIcon(QIcon(":/images/tubiao.png")); // 设置主窗⼝图标
    ui->max->setEnabled(false);

    QGraphicsDropShadowEffect* shadowEffect=new QGraphicsDropShadowEffect(this);
    shadowEffect->setColor("#000000");
    shadowEffect->setBlurRadius(10);//模糊半径
    shadowEffect->setOffset(0,0);//阴影偏移
    this->setGraphicsEffect(shadowEffect);

    // 添加托盘
    // 创建托盘图标
    QSystemTrayIcon *trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/images/tubiao.png"));
    // 创建托盘菜单
    QMenu *trayMenu = new QMenu(this);
    trayMenu->addAction("还原", this, &QWidget::showNormal);
    trayMenu->addSeparator();
    trayMenu->addAction("退出", this, &Widget::quitMymusic);
    // 将托盘菜单添加到托盘图标
    trayIcon->setContextMenu(trayMenu);
    // 显⽰托盘
    trayIcon->show();


    ui->Rec->setIconAndText(":/images/rec.png", "推荐", 1);
    ui->music->setIconAndText(":/images/music.png", "音乐馆", 3);
    ui->audio->setIconAndText(":/images/radio.png", "电台", 2);
    ui->like->setIconAndText(":/images/like.png", "我喜欢", 4);
    ui->local->setIconAndText(":/images/local.png", "本地下载", 5);
    ui->recent->setIconAndText(":/images/recent.png", "最近播放", 6);

    ui->stackedWidget->setCurrentIndex(5);
    currentPage=ui->localPage;
    ui->local->showAnimal(true);

    srand(time(NULL));
    randomPicture();
    ui->recMusicBox->initRecBoxUi(randomPicture(),1);
    ui->supplyMusicBox->initRecBoxUi(randomPicture(),2);

    //设置我喜欢，本地音乐，最近播放页面
    ui->likePage->setCommonPageUI("我喜欢", ":/images/ilikebg.png");
    ui->localPage->setCommonPageUI("本地音乐", ":/images/localbg.png");
    ui->recentPage->setCommonPageUI("最近播放", ":/images/recentbg.png");

    // 按钮的背景图⽚样式去除掉之后，需要设置默认图标
    // 播放控制区按钮图标设定
    ui->play->setIcon(QIcon(":/images/play_2.png")); // 默认为暂停图标
    ui->playMode->setIcon(QIcon(":/images/shuffle_2.png")); // 默认为随机播放

    //初始化音量调节控件
    volumeTool=new VolumeTool(this);

    //初始化lrc对象
    lrcPage=new LrcPage(this);
    lrcPage->hide();
    // lrcPage添加动画效果
    lrcAnimation = new QPropertyAnimation(lrcPage, "geometry", this);
    lrcAnimation->setDuration(250);
    lrcAnimation->setStartValue(QRect(10, 10+lrcPage->height(),lrcPage->width(), lrcPage->height()));
    lrcAnimation->setEndValue(QRect(10, 10, lrcPage->width(), lrcPage->height()));

}

void Widget::initPlayer()
{
    player=new QMediaPlayer(this);
    playList=new QMediaPlaylist(this);

    //设置默认的播放模式
    playList->setPlaybackMode(QMediaPlaylist::Loop);//循环播放

    //将播放器列表给播放器
    player->setPlaylist(playList);

    //设置默认音量
    player->setVolume(20);

    connect(player,&QMediaPlayer::stateChanged,this,&Widget::onPlayStateChanged);

    //当播放的歌曲发生改变时，获取改变后的歌曲
    connect(playList,&QMediaPlaylist::currentIndexChanged,this,&Widget::onCurrentIndexChanged);

    //更新歌曲持续时长
    connect(player,&QMediaPlayer::durationChanged,this,&Widget::onDurationChanged);

    // 播放位置发⽣改变，即已经播放时间更新
    connect(player, &QMediaPlayer::positionChanged, this,&Widget::onPositionChanged);

    //更新歌曲名称和歌手
    connect(player,&QMediaPlayer::metaDataAvailableChanged,this,&Widget::onMetaDataAvailableChanged);
}

void Widget::initSqlite()
{
    //1.加载数据库驱动
    sqlite=QSqlDatabase::addDatabase("QSQLITE");
    //2.设置数据库名称
    sqlite.setDatabaseName("myMusic.db");
    //3.打开
    if(!sqlite.open())
    {
        QMessageBox::critical(this,"打开Music失败",sqlite.lastError().text());
    }

    qDebug()<<"SQLite连接成功，并创建 [myMusic.db] 数据库!!!";

    //4.创建数据库表

    QString sql = ("CREATE TABLE IF NOT EXISTS musicInfo(\
    id INTEGER PRIMARY KEY AUTOINCREMENT,\
    musicId varchar(200) UNIQUE,\
    musicName varchar(50),\
    musicSinger varchar(50),\
    albumName varchar(50),\
    duration BIGINT,\
    musicUrl varchar(256),\
    isLike INTEGER,\
    isHistory INTEGER)"
    );

    QSqlQuery query;
    if(!query.exec(sql))
    {
        QMessageBox::critical(this, "创建数据库表失败",query.lastError().text());
        return ;
    }
    qDebug()<<"创建 [musicInfo] 表成功!!!";

}

void Widget::on_quit_clicked()
{
//    //更新数据库
//    musicList.writeToDB();

//    //关闭数据库连接
//    sqlite.close();

//    close();

    //隐藏到托盘
    hide();
}

void Widget::onBtFormClick(int pageId)
{
    QList<BtForm*> btFormList=this->findChildren<BtForm*>();
    for(auto btFrom:btFormList)
    {
        if(btFrom->getPageId()!=pageId)
        {
            btFrom->clearBackground();
        }
    }
    ui->stackedWidget->setCurrentIndex(pageId-1);
    qDebug()<<"当前页面"<<pageId;

    // 点击btForm时，窗⼝不能拖拽
    isDrag = false;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    // 拦截⿏标左键单击事件
    if(event->button() == Qt::LeftButton)
    {
        isDrag = true;
        // 获取⿏标相对于屏幕左上⻆的全局坐标
        dragPosition = event->globalPos() - frameGeometry().topLeft();
        return;
     }
    QWidget::mousePressEvent(event);
}

void Widget::connectSignalAndSlot()
{
    // ⾃定义的btFrom按钮点击信号，当btForm点击后，设置对应的堆叠窗⼝
    connect(ui->Rec, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->music, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->audio, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->like, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->local, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->recent, &BtForm::btClick, this, &Widget::onBtFormClick);

    connect(ui->likePage,&CommonPage::updateLikeMusic,this,&Widget::onUpdataLikeMusic);
    connect(ui->localPage,&CommonPage::updateLikeMusic,this,&Widget::onUpdataLikeMusic);
    connect(ui->recentPage,&CommonPage::updateLikeMusic,this,&Widget::onUpdataLikeMusic);

    connect(ui->play,&QPushButton::clicked,this,&Widget::playMusic);
    connect(ui->playUp,&QPushButton::clicked,this,&Widget::onPlayUpClicked);
    connect(ui->playDown,&QPushButton::clicked,this,&Widget::onPlayDownClicked);

    //播放模式
    connect(ui->playMode,&QPushButton::clicked,this,&Widget::onPlaybackModeCliked);
    connect(playList,&QMediaPlaylist::playbackModeChanged,this,&Widget::onPlaybackModeChanged);

    //播放所有歌曲的信号的槽函数
    connect(ui->likePage,&CommonPage::playAll,this,&Widget::onPlayAll);
    connect(ui->localPage,&CommonPage::playAll,this,&Widget::onPlayAll);
    connect(ui->recentPage,&CommonPage::playAll,this,&Widget::onPlayAll);

    connect(ui->likePage,&CommonPage::playMusicByIndex,this,&Widget::onPlayMusicByIndex);
    connect(ui->localPage,&CommonPage::playMusicByIndex,this,&Widget::onPlayMusicByIndex);
    connect(ui->recentPage,&CommonPage::playMusicByIndex,this,&Widget::onPlayMusicByIndex);

    //设置静音
    connect(volumeTool,&VolumeTool::setSilence,this,&Widget::setMusicSilence);

    //设置音量大小
    connect(volumeTool,&VolumeTool::setMusicVolume,this,&Widget::onSetMusicVolume);

    // 进度条拖拽
    connect(ui->processBar, &MusicSlider::setMusicSliderPosition, this,&Widget::onMusicSliderChanged);

    //歌词显示
    connect(ui->IrcWord,&QPushButton::clicked,this,&Widget::onLrcWordClicked);
}

QJsonArray Widget::randomPicture()
{
    //推荐文本+图片路径
    QVector<QString> vecImageName;
    vecImageName<<"001.png"<<"003.png"<<"004.png"<<"005.png"<<"006.png"<<"007.png"
    <<"008.png"<<"009.png"<<"010.png"<<"011.png"<<"012.png"<<"013.png"
    <<"014.png"<<"015.png"<<"016.png"<<"017.png"<<"018.png"<<"019.png"
    <<"020.png"<<"021.png"<<"022.png"<<"023.png"<<"024.png"<<"025.png"
    <<"026.png"<<"027.png"<<"028.png"<<"029.png"<<"030.png"<<"031.png"
    <<"032.png"<<"033.png"<<"034.png"<<"035.png"<<"036.png"<<"037.png"
    <<"038.png"<<"039.png"<<"040.png";

    std::random_shuffle(vecImageName.begin(), vecImageName.end());//将元素打散

    //path: ":/images/rec/"+vecImageName[i]
    //text: "推荐-001"
    QJsonArray objArray;
    for(int i=0;i<vecImageName.size();i++)
    {
        QJsonObject obj;
        obj.insert("path",":/images/rec/"+vecImageName[i]);

        QString text=QString("推荐-%1").arg(i,3,10,QChar('0'));
        obj.insert("text",text);

        objArray.append(obj);
    }
    return objArray;
}

void Widget::initMusicList()
{
    //1.从数据库读取歌曲信息
    musicList.readMusicFromDb();

    //2.更新commanPage的页面
    ui->likePage->setMusicListType(PageType::LIKE_PAGE);
    ui->likePage->reFresh(musicList);

    ui->localPage->setMusicListType(PageType::LOCAL_PAGE);
    ui->localPage->reFresh(musicList);

    ui->recentPage->setMusicListType(PageType::HISTORY_PAGE);
    ui->recentPage->reFresh(musicList);

}

void Widget::updateBtformAnimal()
{
    int index=ui->stackedWidget->indexOf(currentPage);
    if(index==-1)
    {
        qDebug()<<"该页面不存在";
    }

    //获取界面上所有的btForm
    QList<BtForm*> btforms=this->findChildren<BtForm*>();
    for(BtForm* btform:btforms)
    {
        if(btform->getPageId()==index+1)
        {
            btform->showAnimal(true);
        }
        else
        {
            btform->showAnimal(false);
        }
    }
}

void Widget::quitMymusic()
{
    musicList.writeToDB();

    sqlite.close();

    if(userDb.isOpen()) {
        userDb.close();
    }

    close();
}



void Widget::playAllMusicOfCommanPage(CommonPage *page, int index)
{
    currentPage=page;
    updateBtformAnimal();

    playList->clear();

    page->addMusicToMediaplayList(musicList,playList);

    //设置当前播放列表的索引
    playList->setCurrentIndex(index);

    //播放
    player->play();
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton && isDrag)
     {
         // 根据⿏标移动更新窗⼝位置
        move(event->globalPos() - dragPosition);
        return;
      }
    QWidget::mouseMoveEvent(event);
}


void Widget::on_volume_clicked()
{
    //1.获取按钮在左上角的图标
    QPoint point=ui->volume->mapToGlobal(QPoint(0,0));

    //2.计算volume窗口在左上角的位置
    QPoint volumeLeftTop=point-QPoint(volumeTool->width()/2,volumeTool->height());
    //volumeLeftTop.setY(volumeLeftTop.y()+30);
    volumeLeftTop.setX(volumeLeftTop.x()+15);

    //3.移动窗口位置
    volumeTool->move(volumeLeftTop);

    //4.显示窗口
    volumeTool->show();
}

void Widget::on_addlocal_clicked()
{
    //1.创建对话框
    QFileDialog fileDialog(this);
    fileDialog.setWindowTitle("添加本地音乐");

    //2.创建一个打开格式的文件对话框
    fileDialog.setAcceptMode(QFileDialog::AcceptOpen);

    //3.设置对话框格式
    //  只能选择文件，并且一次能选多个
    fileDialog.setFileMode(QFileDialog::ExistingFiles);

    // 4. 设置对话框的MIME过滤器
    QStringList mimeList;
    mimeList<<"application/octet-stream";
    fileDialog.setMimeTypeFilters(mimeList);

    // 5. 设置对话框默认的打开路径,设置⽬录为当前⼯程所在⽬录
    QDir dir("E:/myMusic/my-music");
    //dir.cdUp();
    QString musicPath = dir.path()+"/myMusic/musics/";
    fileDialog.setDirectory(musicPath);
    // 6. 显⽰对话框，并接收返回值
    // 模态对话框, exec内部是死循环处理
    if(fileDialog.exec() == QFileDialog::Accepted)
    {
        // 切换到本地⾳乐界⾯，因为加载完的⾳乐需要在本地⾳乐界⾯显⽰
        ui->stackedWidget->setCurrentIndex(4);
        // 获取对话框的返回值
        QList<QUrl> urls = fileDialog.selectedUrls();
        // 拿到歌曲⽂件后，将歌曲⽂件交由musicList进⾏管理
        musicList.addMusicByUrl(urls);

        ui->localPage->reFresh(musicList);

        ui->localPage->addMusicToMediaplayList(musicList,playList);
    }

}

void Widget::onUpdataLikeMusic(bool isLike, QString musicId)
{
    //1.修改状态
    auto it=musicList.findMusicById(musicId);
    if(it!=musicList.end())
    {
        it->setIsLike(isLike);
    }

    //2.通知三个页面更新自己的数据
    ui->likePage->reFresh(musicList);
    ui->localPage->reFresh(musicList);
    ui->recentPage->reFresh(musicList);

    // 更新用户音乐状态
    updateUserMusicStatus(musicId, isLike, it->getIsHistory());
}

void Widget::playMusic()
{
    if(player->state()==QMediaPlayer::PlayingState)
    {
        //正在播放时点击，暂停
        player->pause();
    }
    else if(player->state()==QMediaPlayer::PausedState)
    {
        //暂停状态点击，播放
        player->play();
    }
    else if(player->state()==QMediaPlayer::StoppedState)
    {
        //刚开始时就是停止状态
        player->play();
    }
    else
    {
        qDebug()<<player->errorString();
    }
}

void Widget::onPlayStateChanged()
{
    qDebug()<<"播放状态改变";
    if(player->state()==QMediaPlayer::PlayingState)
    {
        ui->play->setIcon(QIcon(":/images/play_on.png"));
    }
    else
    {
        ui->play->setIcon(QIcon(":/images/play3.png"));
    }
}

void Widget::onPlayUpClicked()
{
    playList->previous();
}

void Widget::onPlayDownClicked()
{
    playList->next();
}

void Widget::onPlaybackModeCliked()
{
    if(playList->playbackMode()==QMediaPlaylist::Loop)//列表循环播放
    {
        ui->playMode->setToolTip("随机播放");
        playList->setPlaybackMode(QMediaPlaylist::Random);
    }
    else if(playList->playbackMode()==QMediaPlaylist::Random)//随机播放
    {
        ui->playMode->setToolTip("单曲循环");
        playList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    }
    else if(playList->playbackMode() == QMediaPlaylist::CurrentItemInLoop)//单曲循环
    {
        ui->playMode->setToolTip("列表循环");
        playList->setPlaybackMode(QMediaPlaylist::Loop);
    }
    else
    {
        qDebug()<<"播放模式错误";
    }
}

void Widget::onPlaybackModeChanged(QMediaPlaylist::PlaybackMode playbackMode)
{
    if(playbackMode == QMediaPlaylist::Loop)
    {
        ui->playMode->setIcon(QIcon(":/images/list_play.png"));
    }
    else if(playbackMode == QMediaPlaylist::Random)
    {
        ui->playMode->setIcon(QIcon(":/images/shuffle_2.png"));
    }
    else if(playbackMode == QMediaPlaylist::CurrentItemInLoop)
    {
        ui->playMode->setIcon(QIcon(":/images/single_play.png"));
    }
    else
    {
        qDebug()<<"暂不⽀持该模式";
    }
}

void Widget::onPlayMusicByIndex(CommonPage *page, int index)
{
    playAllMusicOfCommanPage(page,index);
}

void Widget::onCurrentIndexChanged(int index)
{
    currentMusicIndix=index;

    const QString& musicId=currentPage->getMusicIdByIndex(index);

    auto it=musicList.findMusicById(musicId);
    if(it !=musicList.end())
    {
        it->setIsHistory(true);
        // 更新用户音乐状态
        updateUserMusicStatus(musicId, it->getIsLike(), true);
    }

    ui->recentPage->reFresh(musicList);
}

void Widget::setMusicSilence(bool isMuted)
{
    player->setMuted(isMuted);
}

void Widget::onSetMusicVolume(int volume)
{
    player->setVolume(volume);
}

void Widget::onDurationChanged(qint64 duration)
{
    totalDuration = duration;
    ui->totalTime->setText(QString("%1:%2").arg(duration/1000/60, 2, 10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));
}

void Widget::onPositionChanged(qint64 duration)
{
    ui->currentTime->setText(QString("%1:%2").arg(duration/1000/60, 2, 10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));
    // 界⾯上的进度条也需要同步修改
    ui->processBar->setStep(duration/(float)totalDuration);

    if(currentMusicIndix>=0)
    {
        lrcPage->showLrcWordLine(duration);
    }

}

void Widget::onMetaDataAvailableChanged(bool available)
{
        (int)(available);
        // 歌曲名称、歌曲作者直接到Musci对象中获取
        // 此时需要知道媒体源在播放列表中的索引
        QString musicId = currentPage->getMusicIdByIndex(currentMusicIndix);
        auto it = musicList.findMusicById(musicId);

        QString musicName("未知歌曲");
        QString musicSinger("歌手位置");
        if(it != musicList.end())
        {
            musicName = it->getMusicName();
            musicSinger = it->getSingerName();
        }

        ui->musicName->setText(musicName);
        ui->musicSinger->setText(musicSinger);

        // 获取封面图，通过元数据来获取
        QVariant coverimage = player->metaData("ThumbnailImage");
        if(coverimage.isValid())
        {
            QImage image = coverimage.value<QImage>();
            ui->musicCover->setPixmap(QPixmap::fromImage(image));
            currentPage->setMusicImage(QPixmap::fromImage(image));
        }
        else
        {
            qDebug()<<"歌曲没有封面图";
            // 可以设置默认图片
            QString path = ":/images/rec/001.png";
            ui->musicCover->setPixmap(path);
            currentPage->setMusicImage(path);
        }
        ui->musicCover->setScaledContents(true);

        // 解析歌曲的LRC歌词
        if(it != musicList.end())
        {
            // 获取lrc文件的路径
            QString lrcPath = it->getMusicPath();

            // 解析lrc文件
            lrcPage->parseLrcFile(lrcPath);
        }


}


void Widget::onMusicSliderChanged(float value)
{
    // 1. 计算当前seek位置的时⻓
    qint64 duration = (qint64)(totalDuration * value);
    // 2. 转换为百分制，设置当前时间
    ui->currentTime->setText(QString("%1:%2").arg(duration/1000/60, 2, 10,QChar('0')).arg(duration/1000%60, 2, 10,QChar('0')));
    // 3. 设置当前播放位置
    player->setPosition(duration);

}

void Widget::onLrcWordClicked()
{
    lrcPage->show();
    lrcAnimation->start();
}

void Widget::onPlayAll(PageType pageType)
{
    CommonPage* page=nullptr;
    switch (pageType) {
    case LIKE_PAGE:
        page=ui->likePage;
        break;
    case LOCAL_PAGE:
        page=ui->localPage;
        break;
    case HISTORY_PAGE:
        page=ui->recentPage;
        break;
    default:
        qDebug()<<"未知模式";
        break;
    }

    //开始播放
    playAllMusicOfCommanPage(page,0);
}

void Widget::on_skin_clicked()
{
    QMessageBox::information(this, "温馨提示", "该功能暂不支持...");
}

void Widget::on_max_clicked()
{
    showMaximized();
}

void Widget::on_min_clicked()
{
    showMinimized();
}

void Widget::setCurrentUser(const QString& username)
{
    currentUser = username;
    
    // 先关闭已有的连接
    if(userDb.isOpen()) {
        userDb.close();
    }
    
    // 初始化用户数据库连接
    userDb = QSqlDatabase::addDatabase("QSQLITE", "userConnection");
    userDb.setDatabaseName("myMusic.db");
    
    if (!userDb.open()) {
        QMessageBox::critical(this, "错误", "无法打开数据库");
        return;
    }

    // 确保表存在
    QSqlQuery query(userDb);
    query.exec("CREATE TABLE IF NOT EXISTS user_music_info ("
              "id INTEGER PRIMARY KEY AUTOINCREMENT,"
              "username VARCHAR(50) NOT NULL,"
              "music_id VARCHAR(200) NOT NULL,"
              "is_like INTEGER DEFAULT 0,"
              "is_history INTEGER DEFAULT 0,"
              "last_play_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
              "UNIQUE(username, music_id))");

    // 按顺序初始化
    initMusicList();  // 1. 加载所有音乐
    loadUserMusicData();  // 2. 加载用户的音乐状态
}

void Widget::loadUserMusicData()
{
    if(!userDb.isOpen()) {
        qDebug() << "数据库未打开!";
        return;
    }

    // 先确保清空所有状态
    musicList.clearAllStatus();

    QSqlQuery query(userDb);
    // 使用事务来保证数据一致性
    userDb.transaction();

    query.prepare("SELECT music_id, is_like, is_history FROM user_music_info "
                 "WHERE username = ? ORDER BY last_play_time DESC");
    query.addBindValue(currentUser);
    
    if (!query.exec()) {
        qDebug() << "加载用户数据失败:" << query.lastError().text();
        userDb.rollback();
        return;
    }

    bool hasData = false;
    while (query.next()) {
        hasData = true;
        QString musicId = query.value(0).toString();
        bool isLike = query.value(1).toBool();
        bool isHistory = query.value(2).toBool();

        auto it = musicList.findMusicById(musicId);
        if (it != musicList.end()) {
            qDebug() << "设置音乐状态:" << musicId << isLike << isHistory;
            it->setIsLike(isLike);
            it->setIsHistory(isHistory);
        }
    }

    userDb.commit();

    // 打印当前状态用于调试
    for(auto& music : musicList) {
        qDebug() << "音乐ID:" << music.getMusicId() 
                << "喜欢:" << music.getIsLike() 
                << "历史:" << music.getIsHistory();
    }

    // 刷新所有页面
    ui->likePage->reFresh(musicList);
    ui->localPage->reFresh(musicList);
    ui->recentPage->reFresh(musicList);

    if(hasData) {
        // 如果有数据，切换到最近播放页面
        ui->stackedWidget->setCurrentIndex(5);
        currentPage = ui->recentPage;
        ui->recent->showAnimal(true);
    }
}

void Widget::updateUserMusicStatus(const QString& musicId, bool isLike, bool isHistory)
{
    if (currentUser.isEmpty() || !userDb.isOpen()) {
        qDebug() << "未登录或数据库未打开";
        return;
    }

    QSqlQuery query(userDb);
    query.prepare("INSERT OR REPLACE INTO user_music_info "
                 "(username, music_id, is_like, is_history, last_play_time) "
                 "VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)");
    
    query.addBindValue(currentUser);
    query.addBindValue(musicId);
    query.addBindValue(isLike ? 1 : 0);
    query.addBindValue(isHistory ? 1 : 0);
    
    if (!query.exec()) {
        qDebug() << "更新用户音乐状态失败:" << query.lastError().text()
                 << "\nSQL:" << query.lastQuery()
                 << "\n参数:" << currentUser << musicId << isLike << isHistory;
    } else {
        qDebug() << "成功更新音乐状态:" << musicId << isLike << isHistory;
    }
}
